package org.robot.scm.platform.server.handler.archery;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.infra.RedisCacheHelper;
import org.robot.scm.utils.StreamUtils;

/**
 * @Author : Awn create on 2025/10/17 21:46
 */
@Slf4j
public class ArcheryHelper {

    private static final AtomicInteger LOGIN_COUNT = new AtomicInteger(0);

    private static String getToken() {
        String url = ArcheryConfig.ARCHERY_URL + "/login/";
        HttpRequest httpRequest = HttpUtil.createGet(url);
        HttpResponse execute = httpRequest.execute();
        String cookie = execute.header("Set-Cookie");
        if (StringUtils.isBlank(cookie)) {
            return "";
        }
        String[] cookies = cookie.split(";");
        String csrfToken = StreamUtils.filterOne(Arrays.asList(cookies), cookieInfo -> StringUtils.startsWith(cookieInfo, "csrftoken"));
        return csrfToken.split("=")[1];
    }

    public static void loginAndSession() {
        String user = ArcheryConfig.ARCHERY_USER;
        String password = ArcheryConfig.ARCHERY_PASSWORD;

        String token = getToken();

        String url = ArcheryConfig.ARCHERY_URL + "/authenticate/";
        HttpRequest httpRequest = HttpUtil.createRequest(Method.POST, url);
        httpRequest.header("X-CSRFToken", token);

        HttpResponse httpResponse = httpRequest.body("username=" + user + "&password=" + password).execute();
        String headers = httpResponse.header("Set-Cookie");
        if (StringUtils.isBlank(headers)) {
            return;
        }
        String[] cookies = headers.split(";");
        String sessionCookie = StreamUtils.filterOne(Arrays.asList(cookies), cookieInfo -> StringUtils.startsWith(cookieInfo, "sessionid"));
        String session = sessionCookie.split("=")[1];
        RedisCacheHelper.put("archery_token", token);
        RedisCacheHelper.put("archery_session", session);
        log.info("login archery for {}ths", LOGIN_COUNT.incrementAndGet());
    }
}
